package com.samnative.pineapple.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

import com.samnative.pineapple.main.R;
import com.samnative.pineapple.widget.LoadingDialog;

import java.io.File;
import java.io.IOException;

import id.zelory.compressor.Compressor;

/**
 * 图片压缩
 * Created by Administrator on 2019/5/27.
 */
public class ImgCompress {

    /**
     * 图片压缩保存至本地
     *
     * @param activity   activity对象
     * @param sourceFile 压缩的图片来源
     * @param targetFile 成品保存的位置
     * @param callback   回调 200成功 400失败
     */
    public static void saveImg(Activity activity, File sourceFile, File targetFile, Handler.Callback callback) {

        //图片存在就删除掉
        if (targetFile.getAbsoluteFile().exists()) {
            targetFile.delete();
        }

        //保存的目标目录不存在就创建目录
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }

        LoadingDialog.getInstance(activity).setMessage(activity.getString(R.string.compressing)).show();
        Message msg = Message.obtain();
        try {
            File compressedImage = new Compressor(activity)
                    .setMaxWidth(720)
                    .setMaxHeight(1280)
                    .setQuality(75)
                    .setCompressFormat(Bitmap.CompressFormat.JPEG) //压缩的格式
                    .setDestinationDirectoryPath(activity.getCacheDir().getPath())
                    .compressToFile(sourceFile); //要压缩的图片来源
            boolean is = FileUtils.copyFile(compressedImage.getPath(),
                    targetFile.getPath()); //将成品存到指定的位置
            if (is) {
                msg.what = 200;
            } else {
                msg.what = 400;
            }
        } catch (IOException e) {
            e.printStackTrace();
            msg.what = 400;
        }
        LoadingDialog.dismissDialog();
        callback.handleMessage(msg);
    }
}
